import { reqUser, reqUpdateUser } from '../../api'
/*
  读取query参数指定参数名的值
*/
function getQueryValue(name) {
    let str = location.href.split('?')
    let query = str[1]
    let lets = query.split('&')
    for (let i = 0; i < lets.length; i++) {
        let pair = lets[i].split('=')
        if (pair[0] === name) {
            return pair[1]
        }
    }
}

// 获取用户显示
async function getUser() {
    // 读取id参数
    const id = getQueryValue('id')
    // 请求获取对应的用户
    const result = await reqUser(id)
    const user = result.data
    // 将用户显示到界面上
    document.getElementById('_id').value = user._id
    document.getElementById('username').value = user.username
    document.getElementById('pwd').value = user.pwd
    document.getElementById('preview').src = 'http://localhost:2333' + user.profile
}

// 实现选择图片预览效果
document.getElementById('profile').onchange = (e) => {
    // 得到加载的文件对象
    const file = e.target.files[0]
    // 将file中包含的文件编码为base64字符串
    const fileReader = new FileReader()
    fileReader.readAsDataURL(file)
    fileReader.onload = () => {
        document.getElementById('preview').src = fileReader.result
    }
}

// 通过ajax请求提交更新用户的表单
const updateForm = document.getElementById('updateForm')
updateForm.onsubmit = async (e) => {
    // 阻止事件默认行为
    e.preventDefault()

    // 创建formData对象, 收集表单输入数据
    const formData = new FormData(updateForm)
    // 提交请求
    const { code, msg } = await reqUpdateUser(formData)
    if (code === '200') {
        alert(msg)
    } else {
        window.location = '/users.html'
        alert(msg)
    }
}
getUser().then(() => {})
